//
//  LBPopoverView.m
//  Pods
//
//  Created by LINAICAI on 2017/9/12.
//
//

#import "LBPopoverView.h"
#import "LBPopItem.h"
#import "LBPopItemCell.h"
#import <Masonry/Masonry.h>
// 箭头高度
#define kArrowH 8
// 箭头宽度
#define kArrowW 18
// 视图宽
#define kWith 187
// 视图距离屏幕的间距
#define kSpace 7
// 列表行高
#define kRow_H 55
// 原点的垂直偏移量
#define kOffset 10

@interface LBPopoverView()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
///初始化构造器需要的参数
@property(nonatomic , copy)UIView *view;
@property(nonatomic , assign)CGRect from;
//动画弹出的原点，从from计算出来
@property(nonatomic , assign)CGPoint fromPoint;
@property(nonatomic , assign)LBPopoverArrowPosition positon;
@property(nonatomic , copy)NSArray<LBPopItem*> *items;
///半透明层
@property(nonatomic , strong)UIView *overlayView;
@property(nonatomic , strong)UITableView *tableView;
///全屏覆盖层
@property(nonatomic , strong)UIControl *coverView;
@end
@implementation LBPopoverView
#pragma mark- initialize
+ (void)showInView:(UIView *)view from:(CGRect )from withItems:(NSArray<LBPopItem*> *)items position:(LBPopoverArrowPosition)position{
    [[[LBPopoverView alloc]initWithView:view from:from withItems:items position:position]show];
}
+ (void)showInView:(UIView *)view from:(CGRect )from withItems:(NSArray<LBPopItem*> *)items{
    [[[LBPopoverView alloc]initWithView:view from:from withItems:items position:LBPopoverArrowPositionRight]show];
}
- (instancetype)initWithView:(UIView *)view from:(CGRect )from withItems:(NSArray<LBPopItem*> *)items position:(LBPopoverArrowPosition)position
{
    self = [super init];
    if (self) {
        _view = view;
        _from = from;
        _items = items;
        _positon = position;
        _fromPoint = CGPointMake(from.origin.x + from.size.width/2, from.origin.y + from.size.height/2);
        
        [self setupUI];
        
    }
    return self;
}



#pragma mark- Getter|Setter
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = kRow_H;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.separatorColor = [UIColor colorWithRed:225/255.0 green:229/255.0 blue:232/255.0 alpha:1.0];
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}
- (UIView *)overlayView{
    if (!_overlayView) {
        _overlayView =  [[UIView alloc]initWithFrame:CGRectZero];
        _overlayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        //_overlayView.userInteractionEnabled = YES;
        _overlayView.alpha = 0;
    }
    return _overlayView;
}
- (UIControl *)coverView{
    if (!_coverView) {
        _coverView =  [[UIControl alloc]initWithFrame:CGRectZero];
        _coverView.backgroundColor = [UIColor clearColor];
        [_coverView addTarget:self action:@selector(TapEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coverView;
}
#pragma mark- UITableViewDelegate|UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.items.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *const cellID = @"identity";
    LBPopItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[LBPopItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    LBPopItem *item = self.items[indexPath.row];
    [cell setItem:item];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LBPopItem *item = self.items[indexPath.row];
    if (item.action) {
        item.action();
    }
    [self dismiss:^{

    }];

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark- overwriting
- (void)layoutSubviews{
    [super layoutSubviews];
    
    switch (self.positon) {
        case LBPopoverArrowPositionLeft:
            self.frame = CGRectMake(kSpace, _fromPoint.y + kOffset, kWith, self.items.count * kRow_H + kArrowH);
            break;
        case LBPopoverArrowPositionMiddle:
            self.frame = CGRectMake(UIApplication.sharedApplication.delegate.window.bounds.size.width/2-kWith/2, _fromPoint.y + kOffset, kWith, self.items.count * kRow_H + kArrowH);
            break;
        case LBPopoverArrowPositionRight:
            self.frame = CGRectMake(UIApplication.sharedApplication.delegate.window.bounds.size.width - kWith - kSpace, _fromPoint.y + kOffset, kWith, self.items.count * kRow_H + kArrowH);
            break;
            
        default:
            break;
    }
}


#pragma mark- public
- (void)show{
    __weak typeof(self) weakSelf = self;
    
    CGPoint point = [self convertPoint:_fromPoint fromView:[[UIApplication sharedApplication].delegate window]];
    [self setAnchorPoint:CGPointMake(point.x/kWith, 0.0) forView:self];
    self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
    [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionCurveEaseIn  animations:^{
        weakSelf.transform = CGAffineTransformIdentity;
        weakSelf.overlayView.alpha = 1.0;
        weakSelf.alpha = 1.0;
        
    } completion:^(BOOL finished) {
        
    }];
    
    
}

- (void)dismiss:(void(^)(void))complete{
    __weak typeof(self) weakSelf = self;

    self.transform = CGAffineTransformIdentity;
    [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        weakSelf.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
        weakSelf.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [weakSelf removeFromSuperview];
            [weakSelf.coverView removeFromSuperview];
            
            [UIView animateWithDuration:0.1f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.overlayView.alpha = 0.0;
            } completion:^(BOOL finished) {
                if (finished) {
                    [weakSelf.overlayView removeFromSuperview];
                }
            }];
        }
    }];
}
#pragma mark- liftcycle
- (void)dealloc{
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    NSLog(@"dealloc");
}
#pragma mark- private
- (CAShapeLayer *)createMaskLayer{
    
    CGRect rect  = [self convertRect:self.bounds toView:[[UIApplication sharedApplication].delegate window]];
    
    //路径二
    UIBezierPath *path1 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, kArrowH, rect.size.width, rect.size.height - kArrowH) cornerRadius:5];
    [path1 closePath];
    
    //把外部point转成内部point
    CGPoint point = [self convertPoint:_fromPoint fromView:[[UIApplication sharedApplication].delegate window]];
    CGPoint triangleMiddle = CGPointMake(point.x , 0);
    CGPoint triangleLeft = CGPointMake(point.x  - kArrowW/2, kArrowH);
    CGPoint triangleRight = CGPointMake(point.x  + kArrowW/2, kArrowH);
    
    //路径一
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:triangleLeft];
    [path addLineToPoint:triangleMiddle];
    [path addLineToPoint:triangleRight];
    [path closePath];
    
    //合并路径
    [path1 appendPath:path];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path1.CGPath;
    return layer;
}

- (void)setupUI{
    [self.view addSubview:self.overlayView];
    [self.overlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [UIApplication.sharedApplication.delegate.window addSubview:self.coverView];
    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIApplication.sharedApplication.delegate.window);
    }];
    
    [self.coverView addSubview:self];
    
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self).priorityLow();
        make.top.mas_equalTo(kArrowH);
    }];
    
    [self layoutIfNeeded];
    
    [self.layer setMask:[self createMaskLayer]];
    self.backgroundColor = [UIColor whiteColor];
}

- (void) setAnchorPoint:(CGPoint)anchorpoint forView:(UIView *)view{
    CGRect oldFrame = view.frame;
    CGFloat x = oldFrame.origin.x + anchorpoint.x * view.bounds.size.width;
    CGFloat y = oldFrame.origin.y + anchorpoint.y * view.bounds.size.height;
    view.layer.position = CGPointMake(x , y);
    view.layer.anchorPoint = anchorpoint;
    view.frame = oldFrame;
}
- (void)TapEvent:(id)sender{
    [self dismiss:nil];
}
@end
